import {
  Button,
  Card,
  Cascader,
  Form,
  Icon,
  Input,
  message,
  Modal,
  Popconfirm,
  Radio,
  Select,
  Table,
  Tooltip,
  Upload
} from 'antd'
import OtherSpec from '@/pages/Goods/components/OtherSpec'
import React, { useEffect, useRef, useState } from 'react'
import NewProductSku from '@/pages/Goods/components/NewProductSku'
import { uploadUrl } from '@/config'
import BraftEditor from 'braft-editor'
import { bfUploadFn } from '@/utils/utils'
import GiveBackAddress from '@/pages/Goods/components/GiveBackAddress'
import { LZFormItem } from '@/components/LZForm'
import { getToken } from '@/utils/localStorage'
import addressList from '@/assets/provinceAndCityAndArea.json'
import { isEqual } from 'lodash'
import Prompt from 'umi/prompt'
import router from 'umi/router'
import RouterWillLeave from '@/components/RouterWillLeave'
import Parameters from './components/Parameters'
import { time } from 'mockjs/src/mock/random/date'
import service from '@/pages/Configure/service'

const FormItem = Form.Item
const RadioGroup = Radio.Group

const largeFormItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 3 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 20 }
  }
}
const defaultDetail = {
  goodsDetail: { categoryId: '' },
  categories: [],
  compenRule: [],
  rentRule: [],
  backAddressList: []
}

const GoodsForm = Form.create()(props => {
  const {
    form,
    categories,
    goodsDetail,
    changeSpecs,
    handleSubmit,
    onProductBuyout,
    cancel,
    addServiceTableData = [],
    giveBackList = [],
    deleteSpecs,
    changeSku,
    deleteSku,
    shopAdditionServiceList,
    editShopAdditionServiceList
  } = props
  // console.log(editShopAdditionServiceList, 'editShopAdditionServiceList')
  console.log(shopAdditionServiceList, 'shopAdditionServiceList')
  const { getFieldDecorator } = form
  const {
    categoryId,
    name,
    oldNewDegree,
    labels,
    additionals,
    hasBroken,
    buyOutSupport,
    detail,
    images,
    province,
    city,
    freightType,
    addIds,
    productSkuses = [],
    specs = [],
    rentCycle, // 租赁天数，默认365天
    rentPeriodsType,
    rentPeriods,
    rentDays
  } = goodsDetail
  const [fileList, setFileList] = useState([])
  const [parameters, setParameters] = useState([])
  const [previewImage, setPreviewImage] = useState('')
  const [submitLoading, setSubmitLoading] = useState(false)
  const [isBuyout, setIsBuyout] = useState(buyOutSupport)
  const [isSubmit, setIsSubmit] = useState(false)
  const [originPayload, setOriginPayload] = useState({})
  // 2021-12-19
  const [cycsData, setCycsData] = useState([])
  //增值服务
  const [showShopAdditionService, setShowShopAdditionService] = useState(false)
  const [serviceNameList, setServiceNameList] = useState([])
  const [servicePrice, setServicePrice] = useState('')
  const [serviceNames, setServiceNames] = useState([])

  useEffect(() => {
    if (goodsDetail.productSkuses) {
      const _cycsData = []
      goodsDetail.productSkuses.map((item, index) => {
        _cycsData.push({
          key: index,
          productPackage: item.specAll[0].platformSpecValue,
          color: item.specAll[1].platformSpecValue,
          spec: item.specAll[2].platformSpecValue,
          marketPrice: item.marketPrice,
          salePrice: item.cycs[0].salePrice,
          inventory: item.inventory,
          price: item.cycs[0].price,
          days: 365
          // days: item.cycs[0].days
        })
      })
      setCycsData([..._cycsData])
    }
  }, [goodsDetail.productSkuses])

  categories.map(v => {
    v.children &&
      v.children.map(child => {
        if (child.children && !child.children.length) {
          delete child.children
        }
      })
  })

  let _specs = {}
  let colorSpecs = {}
  let productPackage = {}
  specs.forEach(v => {
    if (v.opeSpecId === 1) {
      productPackage = v
    } else if (v.opeSpecId === 2) {
      colorSpecs = v
    } else {
      _specs = v
    }
  })
  const items = Array.from({ length: 100 }, a => useRef(null))
  // useEffect(() => {
  //   if (editShopAdditionServiceList?.length) {
  //     console.log(editShopAdditionServiceList, 'editShopAdditionServiceList')
  //     let serviceNames = editShopAdditionServiceList?.map((item, index) => {
  //       debugger
  //       return item.shopAdditionalServices.name
  //     })
  //     setServiceNames(serviceNames)
  //     console.log(serviceNames, 'serviceNames')
  //   }
  // }, [editShopAdditionServiceList])
  useEffect(() => {
    setIsBuyout(goodsDetail.buyOutSupport)
  }, [goodsDetail.buyOutSupport])

  useEffect(() => {
    if (detail) {
      props.form.setFieldsValue({
        detail: BraftEditor.createEditorState(detail)
      })
    }
    if (images && images.length) {
      setFileList(
        images.map(v => ({
          uid: v.src,
          url: v.src,
          src: v.src,
          isMain: v.isMain || null
        }))
      )
    }
    setParameters(goodsDetail.parameters)
  }, [detail, images, goodsDetail])

  useEffect(() => {
    // setIsBuyout(goodsDetail.buyOutSupport);
    const values = form.getFieldsValue()
    const payload = getPayload(values)
    setOriginPayload(payload)
  }, [goodsDetail, detail, images, buyOutSupport, parameters])

  const findInitCategory = id => {
    const cates = []
    const findCategoryParentId = category => {
      let result
      const find = e => {
        if (e.value === category) result = e
        if (e.children) {
          for (let i = 0; i < e.children.length; i += 1) {
            find(e.children[i])
          }
        }
      }
      categories.forEach(e => {
        find(e)
      })
      return result
    }
    let element = findCategoryParentId(id)
    if (element) {
      cates.push(element)
    }
    while (element && element.parentId !== 0) {
      element = findCategoryParentId(element.parentId)
      cates.push(element)
    }
    if (cates) {
      return cates
        .map(e => {
          return e.value
        })
        .reverse()
    }
    return []
  }

  // 限制用户上传大小与格式
  const beforeUpload = file => {
    const isJPG =
      file.type === 'image/jpeg' ||
      file.type === 'image/png' ||
      file.type === 'image/gif'
    if (!isJPG) {
      message.error('图片格式不正确')
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      message.error('图片大于2MB')
    }
    return isJPG && isLt2M
  }

  const checkMainImages = (_, value, callback) => {
    if (!value && fileList.length > 0) {
      callback('请上传主图')
      return
    }
    callback()
  }
  const checkprice = (_, value, callback) => {
    if (!productSkuses.length) {
      callback('请填写租金')
      return
    }
    callback()
  }

  const checkDetail = (_, value, callback) => {
    if (value.toHTML() === '<p></p>') {
      callback('请输入商品详情')
      return
    }
    callback()
  }

  const validateAddress = (_rule, value, callback) => {
    if (!value || !value[0] || (!value[1] && province && city)) {
      callback('请选择发货地')
      return
    }
    callback()
  }

  const changeBuyout = evt => {
    const { value } = evt.target
    setIsBuyout(value)
  }

  const handleChangeSpecs = (value, opeSpecId) => {
    if (type === 'buyOutSupport') {
      onProductBuyout(value)
    }
    changeSpecs(value, opeSpecId)
  }

  const handleUploadImage = ({ file, fileList }) => {
    if (file.status === 'done') {
      const images = fileList.map((v, index) => {
        if (v.response) {
          const src = v.response.data
          return { uid: index, src, url: src, isMain: v.isMain || null }
        }
        return v
      })
      setFileList(images)
    }
    if (file.status) {
      setFileList(fileList)
    }
  }

  const handleChangeParam = val => {
    setParameters(val)
  }

  const getPayload = fieldsValue => {
    const payload = fieldsValue
    if (payload.detail) {
      payload.detail = payload.detail.toHTML()
    }
    payload.images = fileList.map((v, index) => {
      if (v.response) {
        const src = v.response.data
        return { uid: index, src, url: src, isMain: v.isMain }
      }
      return v
    })
    let addressObj = {}
    if (fieldsValue.address) {
      addressObj = {
        province: Number(fieldsValue.address[0]),
        city: Number(fieldsValue.address[1])
      }
    }
    return {
      ...payload,
      ...addressObj,
      isBuyout: fieldsValue.isBuyout || fieldsValue.isBuyout === 0 ? 0 : 1,
      parameters
    }
  }

  const handleSubmitForm = e => {
    e.preventDefault()
    productSkuses.map(item => {
      item.cycs[0].days = goodsDetail.rentCycle
    })
    form.validateFieldsAndScroll((err, fieldsValue) => {
      fieldsValue.additionals = fieldsValue.additionals?.map((item, index) => ({
        id: item,
        price: fieldsValue[`price${index}`]
      }))
      if (!err) {
        let hasError = false
        items.map(item => {
          if (item.current) {
            item.current.validateFieldsAndScroll((err, fieldsValue) => {
              if (err) {
                hasError = true
              }
            })
          }
        })
        if (hasError) {
          const errors = document.querySelector('.error-sale')
          if (errors) {
            message.error(`存在${errors.textContent}的输入框`)
            errors.scrollIntoView({ block: 'center' })
          }
        }
        if (!hasError) {
          setSubmitLoading(true)
          setIsSubmit(true)
          const payload = getPayload(fieldsValue)
          handleSubmit(payload).finally(res => {
            setSubmitLoading(false)
          })
        }
      }
    })
  }

  let address = []
  if (province && city) {
    address = [String(province), String(city)]
  }

  const handlePreview = ({ thumbUrl, url }) => {
    const imgUrl = thumbUrl || url
    setPreviewImage(imgUrl)
  }

  const handleCancel = () => {
    // cancel(isPrompt, isSubmit)
  }

  const renderRouterWillLeave = () => {
    // const { isSubmit } = this.state
    const values = props.form.getFieldsValue()
    const payload = getPayload(values)
    const isPrompt = !isEqual(payload, originPayload)
    return <RouterWillLeave isPrompt={isPrompt} isSubmit={isSubmit} />
  }

  const rentCycleChange = e => {
    goodsDetail.rentCycle = e.target.value
  }

  // 2021-12-19 编辑表格逻辑
  const fillPrice = (index, key) => {
    console.log('当前index:' + index)
    console.log('当前key:' + key)
    let _price = 0
    let _cycsData = []
    if (key === 'salePrice') {
      _price = productSkuses[index].cycs[0].salePrice
      // _cycsData[index].salePrice = _price;
    } else if (key === 'price') {
      _price = productSkuses[index].cycs[0].price
      // _cycsData[index].price = _price;
    } else {
      _price = productSkuses[index][key]
      // _cycsData[index][key] = _price;
    }
    for (let i = index; i < productSkuses.length; i++) {
      if (key === 'salePrice') {
        productSkuses[i].cycs[0].salePrice = _price
        // _cycsData[i].salePrice = _price;
      } else if (key === 'price') {
        productSkuses[i].cycs[0].price = _price
        // _cycsData[i].price = _price;
      } else {
        productSkuses[i][key] = _price
        // _cycsData[i][key] = _price;
      }
    }
    productSkuses.map((item, index) => {
      _cycsData.push({
        key: index,
        productPackage: item.specAll[0].platformSpecValue,
        color: item.specAll[1].platformSpecValue,
        spec: item.specAll[2].platformSpecValue,
        marketPrice: item.marketPrice,
        salePrice: item.cycs[0].salePrice,
        inventory: item.inventory,
        price: item.cycs[0].price, // days: 365
        days: item.cycs[0].days
      })
    })
    setCycsData([..._cycsData])
    console.log('cycsData:')
    console.log(cycsData)
    console.log('productSkues:')
    console.log(productSkuses)
  }

  const changeCycs = (evt, inputIndex, key) => {
    if (key === 'salePrice') {
      productSkuses[inputIndex].cycs[0].salePrice = evt.target.value
    } else if (key === 'price') {
      productSkuses[inputIndex].cycs[0].price = evt.target.value
    } else {
      productSkuses[inputIndex][key] = evt.target.value
    }
  }

  const onServiceChange = (value, options) => {
    setServiceNameList(options)
    goodsDetail.hasBroken = false;
    // if(value.length>0){
    //   goodsDetail.hasBroken = true;
    // }else{
    //   goodsDetail.hasBroken = false;
    // }
  }

  const initAdditionals = () => {
    if (editShopAdditionServiceList?.length) {
      const list = editShopAdditionServiceList.map(item =>
        String(item.shopAdditionalServicesId)
      )
      if (list?.length) {
        return list
      }
    }
  }

  useEffect(() => {
    if (editShopAdditionServiceList?.length) {
      setServiceNameList(
        editShopAdditionServiceList.map(item => {
          return {
            props: {
              children: item.shopAdditionalServices?.name
            },
            key: item.shopAdditionalServicesId
          }
        })
      )
    }
  }, [editShopAdditionServiceList])

  // 切换增值服务事件
  const onSelectionChange = (value, options) => {
    setServiceNameList(options)
    options.map(item => {
      if (editShopAdditionServiceList?.length) {
        const aa = editShopAdditionServiceList.find(val => {
          return val.shopAdditionalServicesId === +item.key
        })
        setServicePrice(aa.price)
      } else {
        const aa = shopAdditionServiceList.find(val => {
          return val.id === +item.key
        })
        setServicePrice(aa.price)
      }
    })
  }
  let maxCol = 0
  let packageVal = ''
  for (let i = 0; i < productSkuses.length; i++) {
    if (i === 0) {
      packageVal = productSkuses[i].specAll[0].platformSpecValue
    } else if (packageVal !== productSkuses[i].specAll[0].platformSpecValue) {
      break
    }
    maxCol++
  }

  const initialValue = item => {
    if (editShopAdditionServiceList?.length) {
      return editShopAdditionServiceList.find(service => {
        return service.shopAdditionalServicesId === +item.key
      })?.price
    }
    return shopAdditionServiceList.find(service => {
      return service.id === +item.key
    })?.price
  }

  const cycColumns = [
    {
      title: '套餐',
      dataIndex: 'specAll[0].platformSpecValue',
      render: (value, row, index) => {
        const obj = {
          children: value,
          props: {}
        }
        if (index % maxCol === 0) {
          obj.props.rowSpan = maxCol
        } else {
          obj.props.rowSpan = 0
        }
        return obj
      }
    },
    {
      title: '颜色',
      dataIndex: 'specAll[1].platformSpecValue'
    },
    {
      title: '规格',
      dataIndex: 'specAll[2].platformSpecValue'
    },
    {
      title: '市场价',
      dataIndex: 'marketPrice',
      key: 'marketPrice',
      render: (value, row, index) => {
        return (
          <Form>
            <FormItem style={{ margin: 0 }}>
              <Popconfirm
                title="是否以该价格向下填充？"
                onConfirm={() => fillPrice(index, 'marketPrice')}
              >
                {getFieldDecorator(`cycsdata[${index}]["marketPrice"]`, {
                  initialValue: value,
                  rules: [{ required: true, message: '不能为空' }]
                })(
                  <Input
                    onChange={evt => changeCycs(evt, index, 'marketPrice')}
                  />
                )}
              </Popconfirm>
            </FormItem>
          </Form>
        )
      }
    },
    {
      title: '采购价(参考)',
      dataIndex: 'referPrice',
      key: 'referPrice',
      render: (value, row, index) => {
        return (
          <Form>
            <FormItem style={{ margin: 0 }}>
              <Popconfirm
                title="是否以该价格向下填充？"
                onConfirm={() => fillPrice(index, 'referPrice')}
              >
                {getFieldDecorator(`cycsdata[${index}]["referPrice"]`, {
                  initialValue: value,
                  rules: [{ required: true, message: '不能为空' }]
                })(
                  <Input
                    onChange={evt => changeCycs(evt, index, 'referPrice')}
                  />
                )}
              </Popconfirm>
            </FormItem>
          </Form>
        )
      }
    },
    {
      title: '销售价',
      dataIndex: 'cycs[0].salePrice',
      render: (value, row, index) => {
        return (
          <Form>
            <FormItem style={{ margin: 0 }}>
              <Popconfirm
                title="是否以该价格向下填充？"
                onConfirm={() => fillPrice(index, 'salePrice')}
              >
                {getFieldDecorator(`cycsdata[${index}]["salePrice"]`, {
                  initialValue: value,
                  rules: [{ required: true, message: '不能为空' }]
                })(
                  <Input
                    onChange={evt => changeCycs(evt, index, 'salePrice')}
                  />
                )}
              </Popconfirm>
            </FormItem>
          </Form>
        )
      }
    },
    {
      title: '库存',
      dataIndex: 'inventory',
      key: 'inventory',
      render: (value, row, index) => {
        return (
          <Form>
            <FormItem style={{ margin: 0 }}>
              <Popconfirm
                title="是否以该价格向下填充？"
                onConfirm={() => fillPrice(index, 'inventory')}
              >
                {getFieldDecorator(`cycsdata[${index}]["inventory"]`, {
                  initialValue: value,
                  rules: [{ required: true, message: '不能为空' }]
                })(
                  <Input
                    onChange={evt => changeCycs(evt, index, 'inventory')}
                  />
                )}
              </Popconfirm>
            </FormItem>
          </Form>
        )
      }
    },
    {
      title: '日租金',
      dataIndex: 'cycs[0].price',
      render: (value, row, index) => {
        return (
          <Form>
            <FormItem style={{ margin: 0 }}>
              <Popconfirm
                title="是否以该价格向下填充？"
                onConfirm={() => fillPrice(index, 'price')}
              >
                {getFieldDecorator(`cycsdata[${index}]["price"]`, {
                  initialValue: value,
                  rules: [{ required: true, message: '不能为空' }]
                })(<Input onChange={evt => changeCycs(evt, index, 'price')} />)}
              </Popconfirm>
            </FormItem>
          </Form>
        )
      }
    }
  ]

  // const cycColumns = [{
  //   title: '套餐', dataIndex: 'productPackage', key: 'productPackage', render: (value, row, index) => {
  //     const obj = {
  //       children: value, props: {},
  //     };
  //     if (index % maxCol === 0) {
  //       obj.props.rowSpan = maxCol;
  //     } else {
  //       obj.props.rowSpan = 0;
  //     }
  //     return obj;
  //   }
  // }, {
  //   title: '颜色', dataIndex: 'color', key: 'color',
  // }, {
  //   title: '规格', dataIndex: 'spec', key: 'spec',
  // }, {
  //   title: '市场价', dataIndex: 'marketPrice', key: 'marketPrice', render: (value, row, index) => {
  //     return (<Form>
  //       <FormItem style={{ margin: 0 }}>
  //         <Popconfirm title="是否以该价格向下填充？" onConfirm={() => fillPrice(index, 'marketPrice')}>
  //           {getFieldDecorator(`cycsdata[${index}]["marketPrice"]`, {
  //             initialValue: value, rules: [{ required: true }]
  //           })(<Input onChange={evt => changeCycs(evt, index, 'marketPrice')}/>)}
  //         </Popconfirm>
  //       </FormItem>
  //     </Form>)
  //   }
  // }, {
  //   title: '销售价', dataIndex: 'salePrice', key: 'salePrice', render: (value, row, index) => {
  //     return (<Form>
  //       <FormItem style={{ margin: 0 }}>
  //         <Popconfirm title="是否以该价格向下填充？" onConfirm={() => fillPrice(index, 'salePrice')}>
  //           {getFieldDecorator(`cycsdata[${index}]["salePrice"]`, {
  //             initialValue: value, rules: [{ required: true }]
  //           })(<Input onChange={evt => changeCycs(evt, index, 'salePrice')}/>)}
  //         </Popconfirm>
  //       </FormItem>
  //     </Form>)
  //   }
  // }, {
  //   title: '库存', dataIndex: 'inventory', key: 'inventory', render: (value, row, index) => {
  //     return (<Form>
  //       <FormItem style={{ margin: 0 }}>
  //         <Popconfirm title="是否以该价格向下填充？" onConfirm={() => fillPrice(index, 'inventory')}>
  //           {getFieldDecorator(`cycsdata[${index}]["inventory"]`, {
  //             initialValue: value, rules: [{ required: true }]
  //           })(<Input onChange={evt => changeCycs(evt, index, 'inventory')}/>)}
  //         </Popconfirm>
  //       </FormItem>
  //     </Form>)
  //   }
  // }, {
  //   title: '日租金（365天）', dataIndex: 'price', key: 'price', render: (value, row, index) => {
  //     return (<Form>
  //       <FormItem style={{ margin: 0 }}>
  //         <Popconfirm title="是否以该价格向下填充？" onConfirm={() => fillPrice(index, 'price')}>
  //           {getFieldDecorator(`cycsdata[${index}]["price"]`, {
  //             initialValue: value, rules: [{ required: true }]
  //           })(<Input onChange={evt => changeCycs(evt, index, 'price')}/>)}
  //         </Popconfirm>
  //       </FormItem>
  //     </Form>)
  //   }
  // }];

  return (
    <div className="goods-main">
      <Form {...largeFormItemLayout}>
        {renderRouterWillLeave()}

        <Card bordered={false}>
          <LZFormItem
            label="商品类目"
            field="categoryIds"
            requiredMessage="请选择商品类目"
            initialValue={findInitCategory(categoryId)}
            getFieldDecorator={getFieldDecorator}
          >
            <Cascader placeholder="请选择类目" options={categories || []} />
          </LZFormItem>
          <LZFormItem
            label="商品名称"
            field="name"
            requiredMessage="请输入商品名称"
            getFieldDecorator={getFieldDecorator}
            initialValue={name}
          >
            <Input placeholder="请输入商品名称" />
          </LZFormItem>
          <LZFormItem
            label="商品标准名称"
            field="standardName"
            requiredMessage="请输入商品标准名称"
            getFieldDecorator={getFieldDecorator}
            initialValue={name}
          >
            <Input placeholder="请输入商品名称" />
          </LZFormItem>
          <LZFormItem
            label="产品新旧"
            field="oldNewDegree"
            requiredMessage="请输入产品新旧"
            getFieldDecorator={getFieldDecorator}
            initialValue={oldNewDegree}
          >
            <Radio.Group>
              <Radio value={1}>全新</Radio>
              <Radio value={2}>99新</Radio>
              <Radio value={3}>95新</Radio>
              <Radio value={4}>9成新</Radio>
              <Radio value={5}>8成新</Radio>
              <Radio value={6}>7成新</Radio>
            </Radio.Group>
          </LZFormItem>
          <LZFormItem
            label={
              <label className="">
                租赁标签
                <Tooltip title="租赁标签可多选">
                  <Icon type="info-circle" />
                </Tooltip>
              </label>
            }
            field="labels"
            getFieldDecorator={getFieldDecorator}
            initialValue={labels || undefined}
          >
            <Select mode="tags" placeholder="请输入自定义租赁标签" />
          </LZFormItem>
          <LZFormItem
            label="账单周期类型"
            field="rentPeriodsType"
            getFieldDecorator={getFieldDecorator}
            initialValue={rentPeriodsType}
          >
            <Radio.Group>
              <Radio value={3}>月</Radio>
              <Radio value={2}>周</Radio>
              <Radio value={1}>天</Radio>
            </Radio.Group>
          </LZFormItem>
          <LZFormItem
            label="账单总期数"
            field="rentPeriods"
            getFieldDecorator={getFieldDecorator}
            initialValue={rentPeriods}
          >
            <Input
              style={{ width: '30%' }}
              placeholder="请输入总期数"
              addonAfter="期"
            />
          </LZFormItem>
          <LZFormItem
            label="账单每期数量"
            field="rentDays"
            getFieldDecorator={getFieldDecorator}
            initialValue={rentDays}
          >
            <Input style={{ width: '30%' }} placeholder="请输入每期数量" />
          </LZFormItem>

          <LZFormItem
            label="增值服务"
            field="additionals"
            getFieldDecorator={getFieldDecorator}
            onChange={onServiceChange}
            optionLabelProp="label"
            initialValue={initAdditionals()}
          >
            {shopAdditionServiceList && (
              <Select
                mode="multiple"
                showSearch={false}
              >
                {shopAdditionServiceList?.map(item => (
                  <Select.Option
                    label={item.name}
                    value={String(item.id)}
                    key={String(item.id)}
                    disabled={false}
                  >
                    {item.name}
                  </Select.Option>
                ))}
                {/* {editShopAdditionServiceList?.length
                  ? editShopAdditionServiceList.map((item, index) => {
                      return (
                        <Select.Option key={item.shopAdditionalServices.id}>
                          {item.shopAdditionalServices.name}
                        </Select.Option>
                      )
                    })
                  : shopAdditionServiceList?.map((item, index) => {
                      return (
                        <Select.Option key={item.id}>{item.name}</Select.Option>
                      )
                    })} */}
              </Select>
            )}
          </LZFormItem>

          {serviceNameList.map((item, index) => {
            return (
              <>
                <FormItem
                  {...largeFormItemLayout}
                  label={item.props.children}
                  key={index}
                >
                  {getFieldDecorator(`price${index}`, {
                    initialValue: initialValue(item),
                    rules: [{ required: true, message: '不能为空' }]
                  })(<Input style={{ width: '30%' }} value={item.price} placeholder="请输入" />)}
                </FormItem>
              </>
            )
          })}

          {/*<LZFormItem*/}
          {/*  label="是否包含碎屏险"*/}
          {/*  field="hasBroken"*/}
          {/*  getFieldDecorator={getFieldDecorator}*/}
          {/*  initialValue={hasBroken}*/}
          {/*>*/}
          {/*  <Radio.Group>*/}
          {/*    <Radio value={false}>否</Radio>*/}
          {/*    <Radio value={true}>是</Radio>*/}
          {/*  </Radio.Group>*/}
          {/*</LZFormItem>*/}
          {/*<LZFormItem*/}
          {/*    label={*/}
          {/*      <label className="">*/}
          {/*        增值服务*/}
          {/*        <Tooltip title="增值服务可多选">*/}
          {/*          <Icon type="info-circle" />*/}
          {/*        </Tooltip>*/}
          {/*      </label>*/}
          {/*    }*/}
          {/*    field="additionals"*/}
          {/*    getFieldDecorator={getFieldDecorator}*/}
          {/*    c*/}
          {/*>*/}
          {/*  <Select*/}
          {/*      mode="tags"*/}
          {/*      filterOption={false}*/}
          {/*      onChange={onSelectionChange}*/}
          {/*  >*/}
          {/*    {*/}
          {/*      editShopAdditionServiceList?.length ? editShopAdditionServiceList.map((item,index) => {*/}
          {/*          return <Select.Option key={item.shopAdditionalServices.id}>{item.shopAdditionalServices.name}</Select.Option>*/}
          {/*      }) :*/}
          {/*      shopAdditionServiceList?.map((item,index) => {*/}
          {/*        return <Select.Option key={item.id}>{item.name}</Select.Option>*/}
          {/*      })*/}
          {/*    }*/}
          {/*  </Select>*/}
          {/*</LZFormItem>*/}
          {/* {
            // })

            <FormItem {...largeFormItemLayout} label="增值服务">
              {getFieldDecorator('additionals', {
                // initialValue: serviceNames?.length ? serviceNames : []
              })(
                <Select
                  mode="tags"
                  filterOption={false}
                  onChange={onSelectionChange}
                >
                  {editShopAdditionServiceList?.length
                    ? editShopAdditionServiceList.map((item, index) => {
                        return (
                          <Select.Option key={item.shopAdditionalServices.id}>
                            {item.shopAdditionalServices.name}
                          </Select.Option>
                        )
                      })
                    : shopAdditionServiceList?.map((item, index) => {
                        return (
                          <Select.Option key={item.id}>
                            {item.name}
                          </Select.Option>
                        )
                      })}
                </Select>
              )}
            </FormItem>
          } */}
          {/* {// serviceNameList.map((item,index)=>{
          //   return   <LZFormItem
          //       label={item.label}
          //       field={item.serviceField}
          //       getFieldDecorator={getFieldDecorator}
          //       initialValue={item.price}
          //   >
          //     <Input style={{ width: '30%' }} placeholder="请输入每期数量" />
          //   </LZFormItem>
          // })
          serviceNameList.map((item, index) => {
            return (
              <>
                <FormItem {...largeFormItemLayout} label={item.props.children}>
                  {getFieldDecorator(`price${index}`, {
                    initialValue:
                      shopAdditionServiceList.find(service => {
                        return service.id === +item.key
                      })?.price ||
                      editShopAdditionServiceList.find(service => {
                        return service.shopAdditionalServicesId === +item.key
                      })?.price
                  })(<Input style={{ width: '30%' }} placeholder="请输入" />)}
                </FormItem>
              </>
            )
          })} */}
          {/*<LZFormItem*/}
          {/*  label="增值服务列表"*/}
          {/*  field="shopAdditionals"*/}
          {/*  getFieldDecorator={getFieldDecorator}*/}
          {/*  initialValue={shopAdditionals || undefined}*/}
          {/*>*/}
          {/*  <Select placeholder="请选择" mode="multiple">*/}
          {/*    {addServiceTableData.map(value => {*/}
          {/*      return (<Select.Option value={value.id} label={value.name} key={value.id}>*/}
          {/*        {value.name}*/}
          {/*      </Select.Option>);*/}
          {/*    })}*/}
          {/*  </Select>*/}
          {/*</LZFormItem>*/}
          {/* <LZFormItem */}
          {/*  label="是否可买断" */}
          {/*  field="buyOutSupport" */}
          {/*  requiredMessage="请选择类型" */}
          {/*  getFieldDecorator={getFieldDecorator} */}
          {/*  initialValue={buyOutSupport} */}
          {/* > */}
          {/*  <Radio.Group onChange={changeBuyout}> */}
          {/*    <Radio value={1}>是</Radio> */}
          {/*    <Radio value={0}>否</Radio> */}
          {/*    /!*{buyOutValue === 1 ? <span className="red">{textContent}</span> : null}*!/ */}
          {/*  </Radio.Group> */}
          {/* </LZFormItem> */}
          <FormItem {...largeFormItemLayout} label="套餐名称">
            {getFieldDecorator('productPackage', {
              initialValue: productPackage || []
            })(
              <OtherSpec
                opeSpecId={1}
                key="package"
                onChange={handleChangeSpecs}
              />
            )}
          </FormItem>
          <FormItem {...largeFormItemLayout} label="颜色分类">
            {getFieldDecorator('colorSpecs', {
              initialValue: colorSpecs || []
            })(
              <OtherSpec
                opeSpecId={2}
                key="color"
                onChange={handleChangeSpecs}
              />
            )}
          </FormItem>
          <FormItem {...largeFormItemLayout} label="规格">
            {getFieldDecorator('specs', {
              initialValue: _specs || []
            })(
              <OtherSpec
                opeSpecId={3}
                key="spec"
                onChange={handleChangeSpecs}
              />
            )}
          </FormItem>
          <FormItem label="租金" required>
            {getFieldDecorator('price', {
              rules: [{ validator: checkprice }]
            })(
              <div>
                <Table
                  bordered="true"
                  pagination={false}
                  dataSource={productSkuses}
                  columns={cycColumns}
                />
                {/*{productSkuses.map((p, index) => {*/}
                {/*  return (<NewProductSku*/}
                {/*    getFieldDecorator={getFieldDecorator}*/}
                {/*    oldNewDegree={oldNewDegree}*/}
                {/*    ref={items[index]}*/}
                {/*    key={p.skuId}*/}
                {/*    isBuyout={isBuyout}*/}
                {/*    changeSku={changeSku}*/}
                {/*    deleteSpecs={deleteSpecs}*/}
                {/*    deleteSku={deleteSku}*/}
                {/*    specs={_specs}*/}
                {/*    colorSpecs={colorSpecs}*/}
                {/*    index={index}*/}
                {/*    productSkuses={p}*/}
                {/*  />);*/}
                {/*})}*/}
              </div>
            )}
          </FormItem>
          <FormItem {...largeFormItemLayout} required label="商品图片">
            {getFieldDecorator('images', {
              initialValue: goodsDetail.images,
              rules: [{ validator: checkMainImages }]
            })(
              <div className="upload-desc">
                <Upload
                  accept="image/*"
                  action={uploadUrl}
                  listType="picture-card"
                  headers={{
                    token: getToken()
                  }}
                  fileList={fileList}
                  onPreview={handlePreview} // 预览
                  beforeUpload={beforeUpload}
                  onChange={handleUploadImage}
                >
                  <div>
                    <Icon type="upload" />
                    <div className="ant-upload-text">上传照片</div>
                  </div>
                </Upload>
                <div className="size-desc w294">
                  <span>● 尺寸为700x700px及以上正方形</span>
                  <br />
                  <span>● 不能出现商家logo、水印、电话、微信等联系方式</span>
                  <br />
                  <span>● 其中第一张图要求为纯白色底图</span>
                </div>
              </div>
            )}
          </FormItem>
          <FormItem {...largeFormItemLayout} required label="商品详情">
            {getFieldDecorator('detail', {
              initialValue: BraftEditor.createEditorState(goodsDetail.detail),
              rules: [{ validator: checkDetail }]
            })(
              <BraftEditor
                style={{
                  border: '1px solid #d1d1d1',
                  borderRadius: 5,
                  backgroundColor: '#fff'
                }}
                contentStyle={{
                  height: 500,
                  boxShadow: 'inset 0 1px 3px rgba(0,0,0,.1)'
                }}
                excludeControls={['emoji', 'clear', 'blockquote', 'code']}
                media={{ uploadFn: bfUploadFn }}
              />
            )}
          </FormItem>
          <FormItem
            label="商品参数"
            field="labels"
            getFieldDecorator={getFieldDecorator}
            initialValue={labels || undefined}
          >
            <div>
              <Parameters
                parameters={parameters}
                onChange={handleChangeParam}
              />
            </div>
          </FormItem>

          <Form.Item label="发货地" required>
            {getFieldDecorator('address', {
              rules: [
                {
                  validator: validateAddress
                }
              ],
              initialValue: address
            })(<Cascader options={addressList} placeholder="请选择" />)}
          </Form.Item>
          <LZFormItem
            label="快递"
            field="freightType"
            requiredMessage="请选择快递方式"
            getFieldDecorator={getFieldDecorator}
            initialValue={freightType}
          >
            <Radio.Group>
              <Radio value="FREE">包邮</Radio>
              <Radio value="PAY">到付</Radio>
              <Radio value="SELF">自提</Radio>
            </Radio.Group>
          </LZFormItem>
          <FormItem {...largeFormItemLayout} required label="是否上架">
            {getFieldDecorator('type', {
              initialValue: goodsDetail.type,
              rules: [
                { type: 'number', required: true, message: '请选择是否上架' }
              ]
            })(
              <RadioGroup>
                <Radio value={1}>上架</Radio>
                <Radio value={2}>放入仓库</Radio>
              </RadioGroup>
            )}
          </FormItem>
        </Card>

        <FormItem {...largeFormItemLayout} required label="归还地址">
          {getFieldDecorator('addIds', {
            initialValue: addIds,
            rules: [
              { type: 'array', required: true, message: '请选择归还地址' }
            ]
          })(<GiveBackAddress addressList={giveBackList} />)}
          {/* <Button icon="reload" style={{ margin: 'auto 10px' }} onClick={setInitList} /> */}
          {/* <Button onClick={() => gotoRole('backAddress')}>设置归还地址</Button> */}
        </FormItem>

        <Form.Item wrapperCol={{ offset: 3 }}>
          <Button onClick={cancel} className="w70">
            取消
          </Button>
          <Button
            type="primary"
            loading={submitLoading}
            onClick={handleSubmitForm}
            className="w-112"
          >
            确定
          </Button>
        </Form.Item>

        <Modal
          visible={!!previewImage}
          footer={null}
          onCancel={() => setPreviewImage('')}
          width={600}
        >
          <img
            src={previewImage}
            alt=""
            style={{ width: '100%', paddingTop: 15 }}
          />
        </Modal>
      </Form>
    </div>
  )
})

export default GoodsForm
